package com.estore.src.com.estore02.view;

import com.estore.src.com.estore02.model.Product;
import com.estore.src.com.estore02.service.ProductService;
import com.estore.src.com.estore02.service.ProductSorters;
import java.util.*;

public class ConsoleShop {

    private final ProductService productService = new ProductService();
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

    public void start() {
        System.out.println("🎉 欢迎来到电子商城！");
        System.out.println("📊 当前商品总数: " + productService.getTotalProductCount() + " 件");

        while (true) {
            showMenu();
            String input = scanner.nextLine();

            if (!isValidChoice(input, 1, 7)) {
                // 检查是否为管理员备份功能
                if ("99".equals(input)) {
                    backupData();
                    continue;
                }
                System.out.println("❌ 无效的选项，请重新输入！");
                continue;
            }

            int choice = Integer.parseInt(input);

            switch (choice) {
                case 1:
                    browseProducts();
                    break;
                case 2:
                    browseProductsWithSort();
                    break;
                case 3:
                    searchProduct();
                    break;
                case 4:
                    addToCart();
                    break;
                case 5:
                    viewCart();
                    break;
                case 6:
                    checkout();
                    break;
                case 7:
                    exitSystem();
                    return;
            }
        }
    }

    private void showMenu() {
        System.out.println("\n========== 商城菜单 ==========");
        System.out.println("1. 浏览所有商品（默认排序）");
        System.out.println("2. 排序浏览商品");
        System.out.println("3. 搜索商品");
        System.out.println("4. 添加商品到购物车");
        System.out.println("5. 查看购物车");
        System.out.println("6. 结算");
        System.out.println("7. 退出系统");
        System.out.println("=============================");
        System.out.println("💡 提示: 输入 99 可备份数据文件");
        System.out.print("请输入您的选择: ");
    }

    /**
     * 数据备份功能（管理员功能）
     */
    private void backupData() {
        System.out.println("\n🔒 正在执行数据备份...");
        productService.backupData();
    }

    /**
     * 安全退出系统
     */
    private void exitSystem() {
        System.out.print("是否保存数据后退出？(y/n): ");
        String confirm = scanner.nextLine().trim().toLowerCase();

        if (confirm.equals("y") || confirm.equals("yes")) {
            productService.saveData();
            System.out.println("✅ 数据已保存，感谢使用，再见！");
        } else {
            System.out.println("⚠️  数据未保存，感谢使用，再见！");
        }
    }

    /**
     * 浏览商品（默认排序）
     */
    private void browseProducts() {
        browseProductsWithComparator(null);
    }

    /**
     * 排序浏览商品菜单
     */
    private void browseProductsWithSort() {
        while (true) {
            System.out.println("\n-------- 选择排序方式 --------");
            System.out.println("1. 按商品ID排序（默认）");
            System.out.println("2. 按价格从低到高");
            System.out.println("3. 按价格从高到低");
            System.out.println("4. 按库存从多到少");
            System.out.println("5. 按商品名称排序");
            System.out.println("6. 返回主菜单");
            System.out.println("-----------------------------");
            System.out.print("请选择排序方式: ");

            String input = scanner.nextLine();
            if (!isValidChoice(input, 1, 6)) {
                System.out.println("❌ 无效的选择，请重新输入！");
                continue;
            }

            int sortChoice = Integer.parseInt(input);

            if (sortChoice == 6) {
                break;
            }

            Comparator<Product> comparator = getComparator(sortChoice);
            browseProductsWithComparator(comparator);
        }
    }

    /**
     * 根据选择获取对应的比较器
     */
    private Comparator<Product> getComparator(int choice) {
        switch (choice) {
            case 1: return ProductSorters.BY_ID_ASC;
            case 2: return ProductSorters.BY_PRICE_ASC;
            case 3: return ProductSorters.BY_PRICE_DESC;
            case 4: return ProductSorters.BY_STOCK_DESC;
            case 5: return ProductSorters.BY_NAME_ASC;
            default: return ProductSorters.BY_ID_ASC;
        }
    }

    /**
     * 浏览商品（支持自定义排序）
     */
    private void browseProductsWithComparator(Comparator<Product> comparator) {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts();

        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
            return;
        }

        // 排序处理
        products.sort(comparator);

        // 显示商品
        for (int i = 0; i < products.size(); i++) {
            Product product = products.get(i);
            String stockInfo = product.getStock() > 0 ?
                    String.valueOf(product.getStock()) : "【售罄】";
            System.out.printf("%d. ID: %-5s | 名称: %-20s | 价格: ¥%-8.2f | 库存: %s%n",
                    i + 1, product.getId(), product.getName(), product.getPrice(), stockInfo);
        }

        // 显示当前排序方式和商品统计
        String sortType = getSortType(comparator);
        int availableCount = productService.getAvailableProducts().size();
        System.out.printf("【当前排序: %s | 有库存商品: %d/%d】%n",
                sortType, availableCount, products.size());
    }

    /**
     * 获取排序类型描述
     */
    private String getSortType(Comparator<Product> comparator) {
        if (comparator == ProductSorters.BY_ID_ASC) return "商品ID排序";
        if (comparator == ProductSorters.BY_PRICE_ASC) return "价格从低到高";
        if (comparator == ProductSorters.BY_PRICE_DESC) return "价格从高到低";
        if (comparator == ProductSorters.BY_STOCK_DESC) return "库存从多到少";
        if (comparator == ProductSorters.BY_NAME_ASC) return "商品名称排序";
        return "默认排序";
    }

    /**
     * 搜索商品
     */
    private void searchProduct() {
        System.out.print("请输入商品ID或名称关键字：");
        String keyword = scanner.nextLine().toLowerCase();

        List<Product> products = productService.getAllProducts();
        List<Product> results = new ArrayList<>();

        for (Product product : products) {
            if (product.getId().toLowerCase().contains(keyword) ||
                    product.getName().toLowerCase().contains(keyword)) {
                results.add(product);
            }
        }

        if (results.isEmpty()) {
            System.out.println("未找到相关商品！");
        } else {
            System.out.println("\n========== 搜索结果 ==========");
            for (Product product : results) {
                System.out.println(product);
            }
            System.out.println("=============================");
        }
    }

    /**
     * 添加到购物车
     */
    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine().trim();

        if (!productService.isProductExist(productId)) {
            System.out.println("❌ 错误：商品ID '" + productId + "' 不存在！");
            System.out.println("💡 提示：请先浏览商品查看正确的商品ID");
            return;
        }

        Product product = productService.findProductById(productId);
        System.out.println("📦 商品信息: " + product);

        if (product.getStock() <= 0) {
            System.out.println("❌ 抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量 (库存 " + product.getStock() + "): ");
        String quantityInput = scanner.nextLine();

        if (!isValidNumber(quantityInput)) {
            System.out.println("❌ 错误：请输入有效的正整数！");
            return;
        }

        int quantity = Integer.parseInt(quantityInput);

        if (quantity <= 0) {
            System.out.println("❌ 错误：购买数量必须为正数！");
            return;
        }

        if (!productService.isStockSufficient(productId, quantity)) {
            System.out.println("❌ 错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        int currentQuantity = shoppingCart.getOrDefault(productId, 0);
        shoppingCart.put(productId, currentQuantity + quantity);
        System.out.println("✅ 成功将 " + quantity + " 件 '" + product.getName() + "' 添加到购物车！");
    }

    /**
     * 查看购物车
     */
    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("🛒 购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        int itemCount = 0;

        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);

            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("📦 商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
                itemCount += quantity;
            }
        }

        System.out.println("----------------------------------------");
        System.out.printf("🛍️  商品总数: %d 件\n", itemCount);
        System.out.printf("💰 总计: ¥%.2f\n", total);
    }

    /**
     * 结算功能
     */
    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("❌ 购物车为空，无法结算！");
            return;
        }

        viewCart();

        System.out.print("\n确认结算？(y/n): ");
        String confirm = scanner.nextLine().trim().toLowerCase();

        if (!confirm.equals("y") && !confirm.equals("yes")) {
            System.out.println("💡 已取消结算");
            return;
        }

        boolean allStockSufficient = true;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();

            if (!productService.isStockSufficient(productId, quantity)) {
                Product product = productService.findProductById(productId);
                System.out.println("❌ 错误：商品 '" + product.getName() + "' 库存不足！");
                System.out.println("   所需: " + quantity + "，当前库存: " + product.getStock());
                allStockSufficient = false;
            }
        }

        if (!allStockSufficient) {
            System.out.println("💡 请调整购物车中的商品数量后重新结算");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            int quantity = entry.getValue();
            Product product = productService.findProductById(productId);

            productService.reduceStock(productId, quantity);
            total += product.getPrice() * quantity;

            System.out.printf("✅ 已购买: %s x%d = ¥%.2f%n",
                    product.getName(), quantity, product.getPrice() * quantity);
        }

        System.out.printf("\n🎉 结算成功！总金额：¥%.2f\n", total);
        shoppingCart.clear();
    }

    /**
     * 验证选择是否有效
     */
    private boolean isValidChoice(String input, int min, int max) {
        if (input == null || input.trim().isEmpty()) {
            return false;
        }
        try {
            int choice = Integer.parseInt(input.trim());
            return choice >= min && choice <= max;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    /**
     * 验证输入是否为有效数字
     */
    private boolean isValidNumber(String input) {
        if (input == null || input.trim().isEmpty()) {
            return false;
        }
        try {
            int number = Integer.parseInt(input.trim());
            return number > 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    public static void main(String[] args) {
        new ConsoleShop().start();
    }
}